package com.itheima.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dao.OrderDetailDao;
import com.itheima.pojo.ExcelData;
import com.itheima.pojo.Orders;
import com.itheima.service.AddressBookService;
import com.itheima.service.OrderService;
import com.itheima.service.ShoppingCartService;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    UserService userService;

    @Autowired
    AddressBookService addressBookService;

    @Autowired
    OrderDetailDao orderDetailDao;

    /**
     * 去支付，生成订单
     */
    @PostMapping("/submit")
    public R submitOrders(@RequestBody Orders orders) {
       /* //获取用户id
        Long userId = BaseContext.getCurrentId();
        //1.查看购物车数据
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(qw);
        //2.查看用户数据
        User user = userService.getById(userId);
        //3.查看收货地址
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        //生成订单号
        Long orderNumber = IdWorker.getId();
        //总价初始值
        BigDecimal amount = new BigDecimal("0");

        // 4、保存订单明细数据：点了哪些菜品或套餐
        for (ShoppingCart shop : shoppingCartList) {
            //订单详情实体类
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shop, orderDetail);
            //手动赋值订单id
            orderDetail.setOrderId(orderNumber);
            //计算价格 数量 * 单价
            BigDecimal price = shop.getAmount();
            BigDecimal number = BigDecimal.valueOf(shop.getNumber());
            orderDetail.setAmount(price.multiply(number));
            amount = amount.add(orderDetail.getAmount());//一种菜品的价格，累加
//存入订单详情表中
            orderDetailDao.insert(orderDetail);
        }
        System.out.println("amount = " + amount);
        // 5、保存订单数据，有许多数据需要单独设置
        orders.setNumber(String.valueOf(orderNumber));  //订单号
        orders.setAmount(amount);   //订单总价
        orders.setOrderTime(LocalDateTime.now());   //下单时间
        orders.setCheckoutTime(LocalDateTime.now());    //结账时间
        orders.setUserId(userId);
        orders.setConsignee(addressBook.getConsignee());    //设置收件人姓名
        orders.setUserName(user.getName()); //设置用户名
        orders.setPhone(user.getPhone());   //设置手机号
        orders.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//省+市+区域+详细地址
        orderService.save(orders);
        // 6、删除当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        shoppingCartService.remove(wrapper);*/
        String s = orderService.submitOrders(orders);
        return R.success(s);
    }

    /**
     * 前台
     * 分页查询订单
     */

    @GetMapping("/userPage")
    public R<IPage<Orders>> selectPage(Integer page, Integer pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<Orders> ipage = orderService.page(ordersPage, null);
        return R.success(ipage);

    }
   /* public R<List<Orders>> selectPage() {
        List<Orders> list = orderService.list();
        return R.success(list);
    }*/

    /**
     * 后台
     * 分页查询订单 + 条件查询
     */
    @GetMapping("/page")
    public R<IPage<Orders>> selectPage2(Integer page, Integer pageSize, Long number, @DateTimeFormat(pattern = "yy-MM-dd HH:mm:ss") Date beginTime, @DateTimeFormat(pattern = "yy-MM-dd HH:mm:ss") Date endTime) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.like(number != null,Orders::getNumber,number).between(beginTime != null,Orders::getCheckoutTime,beginTime,endTime);
        Page<Orders> ipage = orderService.page(ordersPage, qw);
        return R.success(ipage);
    }


    /**
     * 修改订单状态
     */
    @PutMapping
    public R<String> updateStatus(@RequestBody Orders orders) {
        orderService.updateById(orders);
        return R.success("修改成功");
    }

    /**
     * 订单明细中新增一个Excel导出功能
     */
    @GetMapping("/export")
    public void exportData(HttpServletResponse response) throws IOException {

        List<Orders> list = orderService.list();

         String fileName = "C:\\Users\\86176\\Desktop\\" + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, ExcelData.class).sheet("订单明细").doWrite(list);
//        FileInputStream fi = new FileInputStream(fileName);
//        ServletOutputStream os = response.getOutputStream();
//        IOUtils.copy(fi,os);
    }


}
